<template>
  <div id="app">
    <!-- 新增按钮和搜索框区域 -->
    <div class="search-container">
      <el-button type="primary" plain @click="openAddDialog">新增</el-button>
      <el-input v-model="search" size="large" placeholder="请输入收货人……" style="margin-left: 20px;" />
    </div>

    <el-table :data="filteredAddresses" style="width: 100%">
      <el-table-column label="收货人" prop="receivename" align="center"/>
      <el-table-column label="电话/手机" prop="receivephone" align="center"/>
      <el-table-column label="所在地区" :formatter="formatRegion" align="center"/>
      <el-table-column label="详细地址" prop="detail" align="center"/>
      <el-table-column label="默认地址" align="center">
        <template #default="scope">
          <div v-if="scope.row.isDefault === 1" style="color: red; font-weight: bold;">
            <el-icon :color="'red'" style="margin-right: 5px;">
              <i class="fas fa-dot-circle"></i>
            </el-icon>
            默认
          </div>
          <el-button v-else size="small" type="primary" @click="setAsDefault(scope.row)">
            设为默认
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">
            修改
          </el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑模态框 -->
    <div v-if="editDialogVisible" class="modal-overlay" @click.self="closeEditDialog">
      <div class="modal">
        <span class="modal-close-button" @click="closeEditDialog">X</span>
        <h2>编辑收货地址</h2>
        <form @submit.prevent="saveEdit">
          <el-form-item label="地址信息：" class="input-group">
            <el-cascader
              v-model="editForm.addressInfo"
              :props="cascaderProps"
              placeholder="请选择地址"
            />
          </el-form-item>
          <el-form-item label="详细地址：" class="input-group">
            <el-input v-model="editForm.detail" placeholder="请输入详细地址" required></el-input>
          </el-form-item>
          <el-form-item label="收货人姓名：" class="input-group" style="margin-left: -15px;">
            <el-input v-model="editForm.receivename" placeholder="请输入收货人姓名" required></el-input>
          </el-form-item>
          <el-form-item label="手机号码：" class="input-group">
            <el-input v-model="editForm.receivephone" placeholder="请输入手机号码" required></el-input>
          </el-form-item>
          <el-form-item class="checkbox-group">
            <el-checkbox v-model="editForm.isDefault">设置为默认收货地址</el-checkbox>
          </el-form-item>
          <button type="submit" class="submit-button">保存</button>
        </form>
      </div>
    </div>

    <!-- 新增模态框 -->
    <div v-if="addDialogVisible" class="modal-overlay" @click.self="closeAddDialog">
      <div class="modal">
        <span class="modal-close-button" @click="closeAddDialog">X</span>
        <h2>新增收货地址</h2>
        <form @submit.prevent="addAddress">
          <el-form-item label="地址信息：" class="input-group">
            <el-cascader
              v-model="newForm.addressInfo"
              :props="cascaderProps"
              placeholder="请选择地址"
            />
          </el-form-item>
          <el-form-item label="详细地址：" class="input-group">
            <el-input v-model="newForm.detail" placeholder="请输入详细地址" required></el-input>
          </el-form-item>
          <el-form-item label="收货人姓名：" class="input-group" style="margin-left: -15px;">
            <el-input v-model="newForm.receivename" placeholder="请输入收货人姓名" required></el-input>
          </el-form-item>
          <el-form-item label="手机号码：" class="input-group">
            <el-input v-model="newForm.receivephone" placeholder="请输入手机号码" required></el-input>
          </el-form-item>
          <el-form-item class="checkbox-group">
            <el-checkbox v-model="newForm.isDefault">设置为默认收货地址</el-checkbox>
          </el-form-item>
          <button type="submit" class="submit-button">保存</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElIcon, ElMessage, ElButton, ElInput, ElFormItem, ElCheckbox, ElCascader, ElMessageBox } from 'element-plus';

export default defineComponent({
  name: 'Address',
  components: {
    ElIcon,
    ElInput,
    ElButton,
    ElFormItem,
    ElCheckbox,
    ElCascader,
  },
  setup() {
    // 值的初始化和函数定义
    const route = useRoute();
    const userId = ref(null);

    const addresses = ref([]);
    const search = ref('');
    const editDialogVisible = ref(false);
    const addDialogVisible = ref(false);

    const editForm = ref({
      addressInfo: [],
      detail: '',
      receivename: '',
      receivephone: '',
      isDefault: false,
    });

    const newForm = ref({
      addressInfo: [],
      detail: '',
      receivename: '',
      receivephone: '',
      isDefault: false,
    });

    const addressOptions = ref([]);

    const cascaderProps = {
      lazy: true,
      lazyLoad(node, resolve) {
        const { level, value } = node;
        // 分级加载地址数据
        if (level === 0) {
          fetchProvinces().then(data => resolve(data.map(prov => ({
            value: prov,
            label: prov,
            leaf: false
          }))));
        } else if (level === 1) {
          fetchCities(value).then(data => resolve(data.map(city => ({
            value: city,
            label: city,
            leaf: false
          }))));
        } else if (level === 2) {
          fetchDistricts(node.parent.value, value).then(data => resolve(data.map(dist => ({
            value: dist,
            label: dist,
            leaf: true
          }))));
        }
      }
    };

    const formatRegion = (row) => `${row.province} ${row.city} ${row.district}`;

    const filteredAddresses = computed(() =>
      addresses.value.filter(
        (addr) =>
          !search.value ||
          addr.receivename
            .toLowerCase()
            .includes(search.value.toLowerCase())
      )
    );

    onMounted(() => {
      userId.value = route.query.userId;
      if (userId.value) {
        fetchAddresses();
      }
    });

    const fetchAddresses = async () => {
      try {
        const response = await axios.get(`http://localhost:8092/address/list`, {
          params: { userId: userId.value }
        });
        addresses.value = response.data;
      } catch (error) {
        console.error('Error fetching address data:', error);
      }
    };

    const fetchProvinces = async () => {
      try {
        const response = await axios.get('http://localhost:8092/alladdress/provinces');
        return response.data;
      } catch (error) {
        console.error('Error fetching provinces:', error);
        return [];
      }
    };

    const fetchCities = async (province) => {
      try {
        const response = await axios.get('http://localhost:8092/alladdress/cities', {
          params: { province },
        });
        return response.data;
      } catch (error) {
        console.error('Error fetching cities:', error);
        return [];
      }
    };

    const fetchDistricts = async (province, city) => {
      try {
        const response = await axios.get('http://localhost:8092/alladdress/districts', {
          params: { province, city },
        });
        return response.data;
      } catch (error) {
        console.error('Error fetching districts:', error);
        return [];
      }
    };

    const openEditDialog = (row) => {
      editForm.value = { ...row, addressInfo: [row.province, row.city, row.district] };
      editDialogVisible.value = true;
    };

    const openAddDialog = () => {
      addDialogVisible.value = true;
    };

    const closeEditDialog = () => {
      editDialogVisible.value = false;
    };

    const closeAddDialog = () => {
      addDialogVisible.value = false;
    };

    const saveEdit = async () => {
      try {
        const { addressInfo, detail, receivename, receivephone, isDefault } = editForm.value;
        const [province, city, district] = addressInfo;
        const addressId = editForm.value.addressId;

        const response = await axios.post('http://localhost:8092/address/update', {
          addressId,
          province,
          city,
          district,
          detail,
          receivename,
          receivephone,
          isDefault: isDefault ? 1 : 0,
          userId: userId.value,
        });

        if (response.data.code == '200') {
          ElMessage({
            message: '地址更新成功',
            type: 'success',
            showClose: true,
          });

          fetchAddresses();
          editDialogVisible.value = false;
        } else {
          ElMessage({
            message: response.data.msg || '地址更新失败',
            type: 'error',
            showClose: true,
          });
        }
      } catch (error) {
        ElMessage({
          message: '更新地址失败，请检查网络连接',
          type: 'error',
          showClose: true,
        });
      }
    };

    const addAddress = async () => {
      try {
        const { addressInfo, detail, receivename, receivephone, isDefault } = newForm.value;
        const [province, city, district] = addressInfo;

        const response = await axios.post('http://localhost:8092/address/add', {
          province,
          city,
          district,
          detail,
          receivename,
          receivephone,
          isDefault: isDefault ? 1 : 0,
          userId: userId.value,
        });

        if (response.data.code == '200') {
          ElMessage({
            message: '地址添加成功',
            type: 'success',
            showClose: true,
          });

          fetchAddresses();
          addDialogVisible.value = false;
        } else {
          ElMessage({
            message: response.data.msg || '地址添加失败',
            type: 'error',
            showClose: true,
          });
        }
      } catch (error) {
        ElMessage({
          message: '添加地址失败，请检查网络连接',
          type: 'error',
          showClose: true,
        });
      }
    };

    const confirmDelete = (row) => {
      ElMessageBox.confirm(
        `此操作将永久删除该地址，是否继续？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => deleteAddress(row))
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        });
    };

    const deleteAddress = async (row) => {
      try {
        const response = await axios.delete(`http://localhost:8092/address/delete`, {
          data: {
            addressId: row.addressId,
            userId: userId.value
          }
        });
        
        if (response.data.code == '200') {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          fetchAddresses();
        } else {
          ElMessage({
            message: response.data.msg || '删除失败',
            type: 'error',
            showClose: true,
          });
        }
      } catch (error) {
        ElMessage({
          message: '删除地址失败，请检查网络连接',
          type: 'error',
          showClose: true,
        });
      }
    };

    const setAsDefault = async (address) => {
      if (!userId.value || !address.addressId) {
        ElMessage({
          message: '缺少必要的信息，无法设置默认地址',
          type: 'warning',
          showClose: true,
        });
        return;
      }

      try {
        const response = await axios.post('http://localhost:8092/address/setDefault', {
          userId: userId.value,
          addressId: address.addressId,
        });

        if (response.data.code == '200') {
          ElMessage({
            message: '默认地址设置成功',
            type: 'success',
            showClose: true,
          });
          fetchAddresses();
        } else {
          ElMessage({
            message: response.data.msg || '设置默认地址失败',
            type: 'error',
            showClose: true,
          });
        }
      } catch (error) {
        ElMessage({
          message: '设置默认地址失败，请检查网络连接',
          type: 'error',
          showClose: true,
        });
      }
    };

    return {
      userId,
      addresses,
      search,
      editDialogVisible,
      addDialogVisible,
      editForm,
      newForm,
      addressOptions,
      filteredAddresses,
      formatRegion,
      openEditDialog,
      openAddDialog,
      closeEditDialog,
      closeAddDialog,
      saveEdit,
      addAddress,
      confirmDelete,
      setAsDefault,
      cascaderProps,
    };
  }
});
</script>

<style scoped>
#app {
  padding: 0;
  margin: 0;
  box-sizing: border-box; /* 因为有全局属性作用域，确保边框和填充是包含在元素的总高度和宽度内 */
}

.search-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 0;
}

.el-input {
  max-width: 200px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.modal-close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  cursor: pointer;
}

.input-group {
  margin-bottom: 20px;
}

.checkbox-group {
  margin-bottom: 20px;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  border-radius: 5px;
  width: 100%;
}

.submit-button:hover {
  background-color: #45a049;
}
</style>
